package com.think.controller;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.think.domain.Condition;
import com.think.domain.ConditionMapper;
import com.think.domain.Value;
import com.think.util.Constants;

@Service
public class ConditionModelController {
	private ConditionMapper conditionMapper;
	private JdbcTemplate jdbcTemplate;

	public ConditionMapper getConditionMapper() {
		return conditionMapper;
	}

	public void setConditionMapper(ConditionMapper conditionMapper) {
		this.conditionMapper = conditionMapper;
	}

	public void setDataSource(DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public int selectCountFromTableById(String tableName, int id){
		return jdbcTemplate
				.queryForInt("SELECT count FROM health." + tableName + " where " + tableName + "_id=" + id + ";"); // Exit
	}
	
	@Transactional(rollbackFor = IllegalArgumentException.class, readOnly=false, timeout=30, 
			propagation=Propagation.SUPPORTS, isolation=Isolation.DEFAULT)
	public boolean insertCondition(Condition condition, String locale) throws IllegalArgumentException{
		int nextValue = getConditionMapper().nextValue("condition");
		condition.setCount(new Long(0));
		condition.setConditionId(nextValue);
		
		Value displayName = new Value();
		displayName.setKeyId(nextValue);
		displayName.setLocale(locale);
		displayName.setValue(condition.getDisplayName());
		displayName.setAttName(Constants.CONDITION_DISPLAY_NAME);
		
		Value discription = new Value();
		discription.setKeyId(nextValue);
		discription.setLocale(locale);
		discription.setValue(condition.getDescription());
		discription.setAttName(Constants.CONDITION_DESCRIPTION);
		
		getConditionMapper().insertCondition(condition);
		getConditionMapper().insertValue(displayName);
		getConditionMapper().insertValue(discription);
		
		throw new IllegalArgumentException();
		
		//return true; //Exit
	}

	@Transactional
	public int updateConditionById(Integer conditionId){
		return 1;
	}
}
